import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:signage/app/constants/template_constants.dart';
import 'package:signage/app/modules/device/models/device_cached_info.dart';
import 'package:signage/app/modules/device/widgets/battery_indicator.dart';
import 'package:signage/app/modules/profile/OTA/controllers/ota_controller.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/selected_shape_view.dart'; // 确保导入正确的路径

class DeviceListItem extends StatefulWidget {
  final DeviceCachedInfo? cachedInfo;
  final Stream<BluetoothConnectionState>? connectionStateStream;
  final Function(String) onRemove;
  final Function()? onTap;
  final bool? showDeleteButton;
  final bool? showUpdateButton;
  final bool? showRssi;
  final Function()? onUpdate;
  final bool? isView;
  final Function(bool)? toggleSelection;
  var isSelected = false;
  final bool? isFromAddDevice;
  final bool needToggleSelection;
  final DfuUpdate? dfuUpdate;
  DeviceListItem({
    super.key,
    required this.cachedInfo,
    this.connectionStateStream,
    required this.onRemove,
    this.onUpdate,
    this.isView,
    this.onTap,
    this.showDeleteButton,
    this.showUpdateButton,
    this.showRssi,
    this.toggleSelection,
    this.isFromAddDevice,
    this.isSelected = false,
    this.needToggleSelection = false,
    this.dfuUpdate,
  });

  @override
  _DeviceListItemState createState() => _DeviceListItemState();
}

class _DeviceListItemState extends State<DeviceListItem> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<BluetoothConnectionState>(
      stream: widget.connectionStateStream,
      initialData: BluetoothConnectionState.disconnected,
      builder: (context, snapshot) {
        return SelectableContainer(
          isSelected: widget.isSelected,
          toggleSelection: () {
            if (widget.needToggleSelection) {
              setState(() {
                widget.isSelected = !widget.isSelected;
              });
              widget.toggleSelection?.call(widget.isSelected);
            }
          },
          child: Container(
            decoration: BoxDecoration(
              color: const Color.fromRGBO(248, 248, 248, 1),
              borderRadius: BorderRadius.circular(8.r),
            ),
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.w),
            child: Column(
              children: [
                Row(
                  children: [
                    (widget.cachedInfo?.canCast ?? false) ||
                            widget.isFromAddDevice == true
                        ? Container(
                            width: 8.w,
                            height: 8.h,
                            decoration: BoxDecoration(
                              color: Color.fromRGBO(0, 202, 7, 1),
                              shape: BoxShape.circle,
                            ),
                          )
                        : Container(
                            width: 8.w,
                            height: 8.h,
                            decoration: BoxDecoration(
                              color: Color.fromRGBO(102, 102, 102, 1),
                              shape: BoxShape.circle,
                            ),
                          ),
                    10.horizontalSpace,
                    Expanded(
                      child: Text(
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        "${widget.cachedInfo?.name}" ?? "",
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                          letterSpacing: 0,
                          color: (widget.cachedInfo?.canCast ?? false) ||
                                  widget.isFromAddDevice == true
                              ? Color.fromRGBO(0, 0, 0, 1)
                              : Color.fromRGBO(153, 153, 153, 1),
                        ),
                      ),
                    ),
                    if (widget.cachedInfo!.displayInfo.isNotEmpty)
                      Text(
                        TemplateConstants.getDeviceScreenSize(
                            widget.cachedInfo!.displayInfo[0].width.toString(),
                            widget.cachedInfo!.displayInfo[0].height
                                .toString()),
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: (widget.cachedInfo?.canCast ?? false) ||
                                  widget.isFromAddDevice == true
                              ? const Color.fromRGBO(98, 98, 98, 1)
                              : Color.fromRGBO(153, 153, 153, 1),
                        ),
                      ),
                  ],
                ),
                6.verticalSpace,
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Text(
                        widget.cachedInfo!.id,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: (widget.cachedInfo?.canCast ?? false) ||
                                  widget.isFromAddDevice == true
                              ? const Color.fromRGBO(102, 102, 102, 1)
                              : const Color.fromRGBO(153, 153, 153, 1),
                        ),
                      ),
                    ),
                    10.horizontalSpace,
                    if (widget.cachedInfo!.firmwareVersion != '--')
                      Text(
                        'v${widget.cachedInfo!.firmwareVersion}',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: (widget.cachedInfo?.canCast ?? false) ||
                                  widget.isFromAddDevice == true
                              ? const Color.fromRGBO(102, 102, 102, 1)
                              : const Color.fromRGBO(153, 153, 153, 1),
                        ),
                      ),
                    if (widget.showRssi == true &&
                        widget.cachedInfo?.rssi != null &&
                        widget.cachedInfo!.firmwareVersion == '--')
                      Text(
                        '${widget.cachedInfo!.rssi.toString()}dBm',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          color: (widget.cachedInfo?.canCast ?? false) ||
                                  widget.isFromAddDevice == true
                              ? const Color.fromRGBO(98, 98, 98, 1)
                              : const Color.fromRGBO(153, 153, 153, 1),
                        ),
                      ),
                  ],
                ),
                6.verticalSpace,
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    if (widget.cachedInfo?.batteryLevel != null)
                      BatteryIndicator(
                        batteryLevel: widget.cachedInfo!.batteryLevel!,
                        canCast: widget.cachedInfo!.canCast ||
                            widget.isFromAddDevice == true,
                      ),
                    if (widget.cachedInfo?.batteryLevel != null)
                      16.horizontalSpace,
                    if (widget.cachedInfo?.displayInfo.isNotEmpty ?? false)
                      Row(
                        children: [
                          Container(
                            padding: EdgeInsets.all(2.w),
                            width: 18.w,
                            height: 13.h,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(2),
                              border: Border.all(
                                color: (widget.cachedInfo?.canCast ?? false) ||
                                        widget.isFromAddDevice == true
                                    ? const Color.fromRGBO(164, 164, 164, 1)
                                    : const Color.fromRGBO(204, 204, 204, 1),
                              ),
                            ),
                            child: Row(
                              children: [
                                Expanded(
                                  child: Container(
                                    color: (widget.cachedInfo?.canCast ??
                                                false) ||
                                            widget.isFromAddDevice == true
                                        ? const Color.fromRGBO(98, 98, 98, 1)
                                        : const Color.fromRGBO(
                                            204, 204, 204, 1),
                                  ),
                                ),
                                if (widget.cachedInfo!.displayInfo.length == 2)
                                  2.horizontalSpace,
                                if (widget.cachedInfo!.displayInfo.length == 2)
                                  Expanded(
                                    child: Container(
                                      color: (widget.cachedInfo?.canCast ??
                                                  false) ||
                                              widget.isFromAddDevice == true
                                          ? const Color.fromRGBO(98, 98, 98, 1)
                                          : const Color.fromRGBO(
                                              204, 204, 204, 1),
                                    ),
                                  ),
                              ],
                            ),
                          ),
                          6.horizontalSpace,
                          Text(
                            widget.cachedInfo!.displayInfo.length == 1
                                ? AppLocalizations.of(context)!
                                    .translate('device_single_screen')
                                : AppLocalizations.of(context)!
                                    .translate('device_dual_screen'),
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w400,
                              color: (widget.cachedInfo?.canCast ?? false) ||
                                      widget.isFromAddDevice == true
                                  ? const Color.fromRGBO(98, 98, 98, 1)
                                  : const Color.fromRGBO(153, 153, 153, 1),
                            ),
                          ),
                          6.horizontalSpace,
                          if (widget.showRssi == true &&
                              widget.cachedInfo?.rssi != null)
                            Text(
                              '${widget.cachedInfo!.rssi.toString()}dBm',
                              style: TextStyle(
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w400,
                                color: (widget.cachedInfo?.canCast ?? false) ||
                                        widget.isFromAddDevice == true
                                    ? const Color.fromRGBO(98, 98, 98, 1)
                                    : const Color.fromRGBO(153, 153, 153, 1),
                              ),
                            )
                        ],
                      ),
                    if (widget.showDeleteButton == true)
                      Row(
                        children: [
                          16.horizontalSpace,
                          GestureDetector(
                            behavior: HitTestBehavior.translucent,
                            onTap: () {
                              if (widget.cachedInfo != null) {
                                widget.onRemove(widget.cachedInfo!.id);
                              }
                            },
                            child: Image.asset(
                              'assets/images/Group 1321318597@2x.png',
                              width: 14.w,
                              height: 14.w,
                            ),
                          ),
                        ],
                      ),
                    Spacer(),
                    if (widget.dfuUpdate != null)
                      GestureDetector(
                        onTap: widget.onUpdate,
                        child: Container(
                          width: 70.w,
                          height: 24.h,
                          decoration: BoxDecoration(
                            color: widget.dfuUpdate!.status ==
                                    DfuUpdateStatus.ready
                                ? Color.fromRGBO(252, 207, 1, 1)
                                : widget.dfuUpdate!.status ==
                                        DfuUpdateStatus.updating
                                    ? Color.fromRGBO(255, 255, 255, 1)
                                    : Color.fromRGBO(0, 207, 59, 1),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              if (widget.dfuUpdate!.status.value ==
                                  DfuUpdateStatus.ready)
                                Image.asset(
                                  'assets/images/Frame@2x (7).png',
                                  width: 20.w,
                                ),
                              if (widget.dfuUpdate!.status.value ==
                                  DfuUpdateStatus.updating)
                                Image.asset(
                                  'assets/images/Group 1321318803@2x.png',
                                  width: 20.w,
                                ),
                              if (widget.dfuUpdate!.status.value ==
                                  DfuUpdateStatus.updating)
                                4.horizontalSpace,
                              Text(
                                  widget.dfuUpdate!.status.value ==
                                          DfuUpdateStatus.ready
                                      ? AppLocalizations.of(context)!
                                          .translate('device_update')
                                      : widget.dfuUpdate!.status.value ==
                                              DfuUpdateStatus.updating
                                          ? AppLocalizations.of(context)!
                                              .translate('device_cancel')
                                          : AppLocalizations.of(context)!
                                              .translate(
                                                  'device_update_success'),
                                  style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w400,
                                      letterSpacing: 0,
                                      color: widget.dfuUpdate!.status ==
                                              DfuUpdateStatus.completed
                                          ? const Color.fromRGBO(
                                              255, 255, 255, 1)
                                          : const Color.fromRGBO(
                                              51, 51, 51, 1)))
                            ],
                          ),
                        ),
                      ),
                  ],
                ),
                if (widget.isView != true)
                  Column(
                    children: [
                      10.verticalSpace,
                      Divider(
                        height: 1.w,
                        color: const Color.fromRGBO(229, 229, 229, 1),
                      ),
                      9.verticalSpace,
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: TextButton(
                              onPressed: widget.cachedInfo?.canCast ?? false
                                  ? widget.onTap
                                  : null,
                              style: TextButton.styleFrom(
                                padding: EdgeInsets.zero,
                                minimumSize: Size.zero,
                                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              ),
                              child: Text(
                                AppLocalizations.of(context)!
                                    .translate('cast_screen'),
                                style: TextStyle(
                                  color: (widget.cachedInfo?.canCast ??
                                              false) ||
                                          widget.isFromAddDevice == true
                                      ? const Color.fromRGBO(98, 98, 98, 1)
                                      : const Color.fromRGBO(153, 153, 153, 1),
                                ),
                              ),
                            ),
                          ),
                          Container(
                            width: 1,
                            height: 20,
                            color: Color.fromRGBO(234, 234, 234, 1),
                          ),
                          Expanded(
                            child: TextButton(
                              onPressed: () =>
                                  widget.onRemove(widget.cachedInfo!.id),
                              style: TextButton.styleFrom(
                                padding: EdgeInsets.zero,
                                minimumSize: Size.zero,
                                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                              ),
                              child: Text(
                                AppLocalizations.of(context)!
                                    .translate('device_unbind'),
                                style: TextStyle(
                                  color: const Color.fromRGBO(255, 0, 0, 1),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                if (widget.dfuUpdate != null && widget.dfuUpdate!.progress != 0)
                  Column(
                    children: [
                      5.verticalSpace,
                      LinearProgressIndicator(
                        minHeight: 3.h,
                        value: widget.dfuUpdate!.progress
                            .value, // Example value, replace with actual progress
                        backgroundColor: Color.fromRGBO(248, 248, 248, 1),
                        valueColor: AlwaysStoppedAnimation<Color>(
                            Color.fromRGBO(252, 207, 1, 1)),
                      ),
                    ],
                  ),
              ],
            ),
          ),
        );
      },
    );
  }
}
